//
//  NSString+scca_sm3.m
//  AlgorithmDemo
//
//  Created by cyptt on 2022/3/2.
//

#import "NSString+scca_sm3.h"
#import "scca_sm3.h"
@implementation NSString (scca_sm3)

- (NSData *)scca_sm3Data{
    if (!self.length) {
        return nil;
    }
    NSData *data = [self dataUsingEncoding:NSUTF8StringEncoding];
    int dataLength = (int)data.length;
    unsigned char dataArr[dataLength];
    memcpy(dataArr, data.bytes, dataLength);
    int outputLength = 32;
    unsigned char output[outputLength];
    scca_sm3(dataArr, dataLength, output);
    return [NSData dataWithBytes:output length:outputLength];
}
- (NSString *)scca_sm3{
    NSData *sm3Data = [self scca_sm3Data];
    NSString *sm3Str = [self convertDataToHexStr:sm3Data];
    return sm3Str;
}
// NSData转16进制 第一种
- (NSString *)convertDataToHexStr:(NSData *)data
{
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    return string;
}
@end
